import { login, logout, getInfo ,smsCodeLogin } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles:null,
    mobile:'',
    adminId:'',
    kingId:'',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLE: (state, roles) => {
      state.roles = roles;
    },
    SET_ADMINID: (state, id) => {
      state.adminId = id;
    },
    SET_KINGID: (state, id) => {
      state.kingId = id;
    },
    SET_MOBILE:(state, mobile) =>{
      state.mobile = mobile
    }
  },

  actions: {
    // 登录
    Login({ commit }, param) {
      const username = param.data.username.trim()
      return new Promise((resolve, reject) => {
        if (param.isPwd){ //密码登录
          login(username, param.data.password).then(response => {
            const data = response;
            const tokenStr = 'Bearer '+data;
            setToken(tokenStr)
            commit('SET_TOKEN', tokenStr);
            resolve()
          }).catch(error => {
            reject(error)
          })
        } else{ //短信登录
          smsCodeLogin(param.data.phone, param.data.code).then(response => {
            const data = response;
            const tokenStr = 'Bearer '+data;
            setToken(tokenStr)
            commit('SET_TOKEN', tokenStr);
            resolve()
          }).catch(error => {
            reject(error)
          })
        }

      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response;
          if (data.admin_id) { // 验证返回用户信息是否有值
            commit('SET_ADMINID', data.admin_id);
            commit('SET_ROLE', data.role)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_KINGID', data.king_id);
          commit('SET_NAME', data.admin_realname);
          commit('SET_AVATAR', data.icon);
          commit('SET_MOBILE',data.admin_mobile);
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        // logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', '')
          commit('SET_ADMINID', '')
          localStorage.clear();
          removeToken()
          resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
